<!-- 管理员信息 -->
<script setup lang="ts">
import {
  manDelistData,
  manEditListData,
  manAddListData,
  getManagerPage,
  updateManagerPassword,
  getUserForm,
} from "@/api/userinfo/manager/index";
import {
  MannagerQuery,
  ManagerForm,
  ManagerPageVO,
} from "@/api/userinfo/manager/types";

import { useUserStore } from "@/store/modules/user";

const { user } = useUserStore();

const queryFormRef = ref(ElForm); // 查询表单
const mangerFormRef = ref(ElForm); //管理员表单

const loading = ref(false); //加载状态
const queryParams = reactive<MannagerQuery>({
  page: 1,
  pageSize: 10,
});

const total = ref(0); // 数据总数
const pageData = ref<ManagerPageVO[]>(); // 用户分页数据

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "manager-form",
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<ManagerForm>({
  status: "1",
});

const rules = reactive({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  deptId: [{ required: true, message: "请输入学院", trigger: "blur" }],
  position: [{ required: true, message: "请输入职位", trigger: "blur" }],
  phone: [
    {
      required: true,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  roleId: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getManagerPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

/** 重置密码 */
function resetPassword(id: string, username: string) {
  // 调用ElMessageBox的confirm方法显示一个确认对话框
  if (username == user.username) {
    ElMessageBox.confirm(
      "您确定要重置此用户的密码?", // 对话框的内容
      "重置密码", // 对话框的标题
      {
        confirmButtonText: "确认", // 确认按钮的文本
        cancelButtonText: "取消", // 取消按钮的文本
        type: "warning", // 对话框的类型
      }
    ).then(() => {
      // 如果用户点击了确认按钮，显示一个成功消息
      updateManagerPassword(id).then(() => {
        ElMessage.success("密码重置成功，新密码是：123456");
      });
    });
  } else {
    ElMessage.error("您只能重置自己的账号密码");
  }
}

/**
 * 打开弹窗
 */
function openDialog(type: string, id?: string) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "manager-form") {
    // 用户表单弹窗
    if (id) {
      dialog.title = "修改管理员";
      getUserForm(id).then(({ data }) => {
        Object.assign(formData, { ...data });
      });
    } else {
      dialog.title = "新增管理员";
    }
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：manager-form
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "manager-form") {
    mangerFormRef.value.resetFields();
    mangerFormRef.value.clearValidate();

    formData.id = undefined;
    formData.status = "1";
  }
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (dialog.type === "manager-form") {
    mangerFormRef.value.validate((valid: any) => {
      if (valid) {
        const userId = formData.id;
        loading.value = true;
        const name = formData.name;
        console.log(name);

        if (userId) {
          ElMessageBox.confirm("确认修改管理员？", "警告", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }).then(function () {
            if (name) {
              manEditListData(formData, name)
                .then(() => {
                  ElMessage.success("修改管理员成功");
                  closeDialog();
                  resetQuery();
                })
                .finally(() => (loading.value = false));
            }
          });
        } else {
          ElMessageBox.confirm("确认添加管理员？", "警告", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }).then(function () {
            manAddListData(formData)
              .then(() => {
                ElMessage.success("新增管理员成功");
                closeDialog();
                resetQuery();
              })
              .finally(() => (loading.value = false));
          });
        }
      }
    });
  }
}, 3000);

/** 删除用户 */
function handleDelete(id?: string) {
  if (id) {
    ElMessageBox.confirm("确认删除管理员?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(function () {
      manDelistData(id).then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      });
    });
  }
}
onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!-- 用户列表 -->
    <div class="search-container">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
        label-width="100px"
        class="form-container"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            placeholder="姓名"
            clearable
            v-model="queryParams.name"
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="学院" prop="deptId">
          <el-input
            placeholder="学院"
            clearable
            v-model="queryParams.deptId"
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="职位" prop="position">
          <el-input
            placeholder="职位"
            clearable
            v-model="queryParams.position"
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input
            placeholder="电话号码"
            clearable
            v-model="queryParams.phone"
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="账号" prop="userName">
          <el-input
            placeholder="账号"
            clearable
            v-model="queryParams.userName"
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-input
            placeholder="角色"
            clearable
            v-model="queryParams.roleId"
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <!-- v-model="queryParams.status" -->
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="!w-[200px]"
          >
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item class="handleQuery">
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!-- <template #header>
        <div class="flex justify-between">
          <div>
            <el-button type="success" @click="openDialog('manger-form')"
              ><i-ep-plus />新增</el-button
            >
          </div>
        </div>
      </template> -->

      <el-table v-loading="loading" :data="pageData" style="width: 100%">
        <el-table-column label="姓名" align="center" width="120" prop="name" />

        <el-table-column
          label="学院"
          align="center"
          width="200"
          prop="deptId"
        />

        <el-table-column
          label="职位"
          align="center"
          width="200"
          prop="position"
        />

        <el-table-column
          label="电话号码"
          align="center"
          width="130"
          prop="phone"
        />

        <el-table-column
          label="账号"
          align="center"
          width="130"
          prop="username"
        />

        <el-table-column
          label="角色"
          align="center"
          width="130"
          prop="roleId"
        />

        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status == '1' ? 'success' : 'info'">{{
              scope.row.status == "1" ? "启用" : "禁用"
            }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="220">
          <!-- #default="scope" -->
          <template #default="scope">
            <!-- @click="resetPassword(scope.row)" -->
            <el-button
              type="primary"
              size="small"
              link
              @click="resetPassword(user.id, scope.row.username)"
              ><i-ep-refresh-left />重置密码</el-button
            >

            <el-button
              type="primary"
              link
              size="small"
              @click="openDialog('manager-form', scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >

            <el-button
              type="primary"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        ref="mangerFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input placeholder="请输入姓名" v-model="formData.name" />
        </el-form-item>
        <el-form-item label="学院" prop="deptId">
          <el-input placeholder="请输入学院" v-model="formData.deptId" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input placeholder="请输入职位" v-model="formData.position" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input placeholder="请输入电话号码" v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input placeholder="请输入账号" v-model="formData.username" />
        </el-form-item>
        <!-- <el-form-item label="角色" prop="roleId">
          <el-input placeholder="请输入角色" v-model="formData.roleId" />
        </el-form-item> -->
        <el-form-item label="使用状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="'1'">启用</el-radio>
            <el-radio :label="'0'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- #footer="scope" -->
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 认</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.form-container {
  display: flex;
  flex-wrap: wrap;
}

.handleQuery {
  margin-left: auto;
}
</style>
